package org.gosdt.ew.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import org.gosdt.ew.model.DataBaseAccess;
import org.gosdt.ew.model.Languages;

public class LanguagesDBAccess extends DataBaseAccess {

	private Languages languages;

	public LanguagesDBAccess(Languages languages) {
		super("Languages");
		this.languages = languages;
	}

	public static LanguagesDBAccess create(Languages languages) {
		return new LanguagesDBAccess(languages);
	}

	/**
	 * Get all languages in DB
	 * 
	 * @return array list of languages
	 */
	public ArrayList<Languages> getListInDB() {
		ResultSet rs = getListByDetail(null);
		ArrayList<Languages> myData = new ArrayList<Languages>();
		try {
			while (rs.next()) {
				Languages item = new Languages();
				item.setExist(true);
				item.setName(rs.getString(1));
				myData.add(item);
			}
			rs.close();
			return myData;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}

	}
	
	@Override
	protected final ResultSet getListByDetail(HashMap<?, ?> keys) {
		String selectSQL = "SELECT * From Languages";
		try {
			EWDataBase db = EWDataBase.getInstance();
			return db.getConn().prepareStatement(selectSQL).executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static Languages GetOneRowByName(String languageName) {
		Languages newInstance = new Languages();
		String selectSQL = "SELECT * From Languages WHERE name = '"
				+ languageName + "'";
		try {
			EWDataBase db = EWDataBase.getInstance();
			ResultSet rs = db.getConn().prepareStatement(selectSQL)
					.executeQuery();
			if (rs.next()) {
				newInstance.setExist(true);
				newInstance.setName(rs.getString(1));
			} else {
				newInstance.setExist(false);
				newInstance.setName(languageName);
			}
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return newInstance;
	}

	public int insertCurRecord() {
		if (languages.isExists())
			return DataBaseAccess.RECORD_EXISTS_IN_TABLE;
		HashMap<String, String> insertValues = new HashMap<String, String>();
		insertValues.put("NAME", languages.getName());
		return super.insertOneRecord(insertValues);
	}
}
